<template>
  <div class="login-vue" :style="bg">
    <div class="container">
      <p class="title">WELCOME</p>
      <div class="input-c">
        <Input prefix="ios-contact" v-model="account" placeholder="用户名" clearable @on-blur="verifyAccount"/>
        <p class="error">{{accountError}}</p>
      </div>
      <div class="input-c">
        <Input type="password" v-model="pwd" prefix="md-lock" placeholder="密码" clearable @on-blur="verifyPwd"/>
        <p class="error">{{pwdError}}</p>
      </div>
      <Button :loading="isShowLoading" class="submit" type="primary" @click="submitLogin">登陆</Button>
      <p class="account"><span @click="register">注册账号</span> | <span @click="forgetPwd">忘记密码</span></p>
    </div>
  </div>
</template>

<script>

  import {getCurrent} from '@/api/adminApi';
  import {currentMenu} from '@/api/menuAPi';
  import {securityLogin} from '@/api/gatewayApi';
  import PubSub from 'pubsub-js' //引入PubSub
  export default {
    name: 'login',
    data() {
      return {
        account: 'superAdmin',
        pwd: 'admin',
        accountError: '',
        pwdError: '',
        isShowLoading: false,
        bg: {},
      }
    },
    created() {
      this.bg.backgroundImage = 'url(' + require('../assets/imgs/bg0' + new Date().getDay() + '.jpg') + ')'
    },
    watch: {
      $route: {
        handler(route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true,
      },
    },
    methods: {
      verifyAccount() {
       /* if (this.account !== 'admin') {
          this.accountError = '账号为admin'
        } else {
          this.accountError = ''
        }*/
      },
      verifyPwd() {
      /*  if (this.pwd !== 'admin') {
          this.pwdError = '密码为admin'
        } else {
          this.pwdError = ''
        }*/
      },
      register() {
        //注册 todo
      },
      forgetPwd(messageObj) {

      },
      connectWebSocket(token) {
       let _self = this;
        let replaceToken = token.replace(/Beare /g,"");
        let websocket = null;
        if ('WebSocket' in window) {
          //todo webSocket连接地址配置
          websocket = new WebSocket("ws://127.0.0.1:9096/ws?token=" + replaceToken);
        } else {
          console.error("您的浏览器不支持webSocket....");
        }
        websocket.onerror = function () {
          console.error("webSocket连接异常....");
        };
        websocket.onopen = function () {
          console.log("webSocket连接成功....");
        };
        websocket.onmessage = function (event) {
          console.log("接收到服务端发送的消息:",event.data);
          //通知leftMenu.vue组件刷新消息数量
          let messageObj = {
            content:event.data
          }
          //消息发布,在其他组件中订阅
          PubSub.publish("messageNotify",messageObj);
        };
        websocket.onclose = function () {
          console.log("webSocket连接断开....");
        };
        window.onbeforeunload = function () {
          websocket.close(3000,"强制关闭");
        }
      },
      submitLogin() {
        securityLogin(this.account,this.pwd).then(res => {
          if(res.data.code == 200){
            // 登陆成功
            console.log("登录返回的：",res.data.data)
            window.localStorage.setItem('token', res.data.data);
            window.sessionStorage.removeItem("menuData");
            //登录成功,请求获取用户的信息
            getCurrent().then(res => {
              if(res.data.code == 200){
                localStorage.setItem('userImg', res.data.data.avatar);
                localStorage.setItem('userName', res.data.data.userName);
              }
            });
          // 请求菜单权限数据
            currentMenu().then(res => {
              if(res.data.code == 200){
                //TODO 设置store中state的菜单数据,填充后台返回的菜单数据
                this.$store.commit("setMenus", res.data.data.menuTreeList);
                //将按钮权限存入缓存
                const buttonStr = JSON.stringify(res.data.data.buttonUrlList);
                window.sessionStorage.setItem("btnPermission",buttonStr)
                this.isShowLoading = true;
                this.$router.push({name:'home'})
              }
            });
            //连接webSocket
            this.connectWebSocket(res.data.data);
          }else{
              this.$Message.error(res.data.msg);
          }
        });
      },
    },
  }
</script>

<style>
  .login-vue {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
  .login-vue .container {
    background: rgba(255, 255, 255, .5);
    width: 300px;
    text-align: center;
    border-radius: 10px;
    padding: 30px;
  }
  .login-vue .ivu-input {
    background-color: transparent;
    color: #fff;
    outline: #fff;
    border-color: #fff;
  }
  .login-vue ::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color: rgba(255, 255, 255, .8);
  }
  .login-vue :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color: rgba(255, 255, 255, .8);
  }
  .login-vue ::-moz-placeholder { /* Mozilla Firefox 19+ */
    color: rgba(255, 255, 255, .8);
  }
  .login-vue :-ms-input-placeholder { /* Internet Explorer 10-11 */
    color: rgba(255, 255, 255, .8);
  }
  .login-vue .title {
    font-size: 16px;
    margin-bottom: 20px;
  }
  .login-vue .input-c {
    margin: auto;
    width: 200px;
  }
  .login-vue .error {
    color: red;
    text-align: left;
    margin: 5px auto;
    font-size: 12px;
    padding-left: 30px;
    height: 20px;
  }
  .login-vue .submit {
    width: 200px;
  }
  .login-vue .account {
    margin-top: 30px;
  }
  .login-vue .account span {
    cursor: pointer;
  }
  .login-vue .ivu-icon {
    color: #eee;
  }
  .login-vue .ivu-icon-ios-close-circle {
    color: #777;
  }
</style>
